import type { IClientFile } from '@/interfaces';
import { type MouseEventHandler, useState } from 'react';
import classNames from 'classnames';
import Image from 'next/image';

export default function FileItem({
  item,
  onClickItem,
  itemIndex,
  oss,
}: {
  item: IClientFile;
  onClickItem: MouseEventHandler;
  itemIndex: number;
  oss?: string;
}) {
  const url = oss ? oss + item.urls.default : item.urls.default;
  const [load, setLoad] = useState(false);

  function onLoad() {
    setLoad(true);
  }

  return (
    <div
      onClick={onClickItem}
      className={classNames(
        'card cursor-pointer position-relative user-select-none',
        {
          'border-success': itemIndex === item.id,
        },
      )}
      style={{ width: '12rem', height: '15rem' }}
    >
      <div className="ratio ratio-4x3">
        {item.isImage ? (
          <>
            {!load && (
              <div className="d-flex justify-content-center align-items-center text-secondary">
                <p className="placeholder-glow w-25 mb-0">
                  <span className="placeholder col-12"></span>
                </p>
              </div>
            )}
            <Image
              src={url}
              alt={item.originalName}
              onLoad={onLoad}
              className="object-fit-contain"
              fill
              sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
            />
          </>
        ) : (
          <div className="d-flex justify-content-center align-items-center text-secondary text-uppercase">
            {item.extension || 'FILE'}
          </div>
        )}
      </div>
      <div className="card-body">
        {item.isImage && !load ? (
          <>
            <p className="card-title placeholder-glow">
              <span className="placeholder col-8"></span>
            </p>
            <p className="card-text placeholder-glow">
              <span className="placeholder col-6"></span>
            </p>
          </>
        ) : (
          <>
            <p className="card-title text-truncate">{item.originalName}</p>
            <p className="card-text text-secondary">
              {Math.ceil(item.size / 1024)}KB
            </p>
          </>
        )}
      </div>
      {itemIndex === item.id && (
        <div className="position-absolute top-50 start-50 translate-middle">
          <div className="animate__animated animate__pulse">
            <i className="bi bi-check2-circle text-success fs-4"></i>
          </div>
        </div>
      )}
    </div>
  );
}
